from nicegui import ui

class FloatingButton:
    def __init__(self):
        # 用于存储变量名、值和序号
        self.variables = {}
        self.next_index = 1
        # 创建悬浮按钮
        with ui.footer().classes('fixed bottom-4 right-4 z-50 bg-primary text-white p-4 rounded-full shadow-lg hover:bg-primary-800 transition-all cursor-pointer').on('click', self.toggle_panel):
            ui.icon('add').classes('text-2xl')
        
        # 创建悬浮面板（初始隐藏），进一步加宽面板
        self.panel = ui.element('div').classes('fixed bottom-20 right-4 bg-white rounded-lg shadow-xl p-4 w-[560px] z-40 transform translate-y-full opacity-0 transition-all duration-300 pointer-events-none')
        
        # 使用 with 语句将内容添加到面板
        with self.panel:
            # 面板头部，包含关闭按钮
            with ui.row().classes('justify-between items-center mb-3'):
                ui.label('这是一个悬浮面板').classes('font-bold text-lg')
                ui.button(on_click=self.hide_panel).props('flat icon=close')
            ui.separator()
            
            # 设置面板内容区域最大高度为视口高度
            self.panel_content = ui.column().classes('w-full').style('max-height: 100vh; overflow-y: auto;')
            
            # 添加变量按钮
            ui.button('添加变量', on_click=self.add_variable_row).classes('w-full mt-3')
            # 添加更新按钮，用于手动触发根据字典更新变量行
            ui.button('根据字典更新变量', on_click=self.update_variables_from_dict).classes('w-full mt-2')
        
        self.visible = False
        # 初始化时根据字典内容创建变量行
        self.update_variables_from_dict()

    def toggle_panel(self):
        print(f"点击按钮，当前面板可见状态: {self.visible}")  # 添加调试信息
        if self.visible:
            self.hide_panel()
        else:
            self.show_panel()

    def show_panel(self):
        print("尝试显示面板")  # 添加调试信息
        self.panel.classes(remove='translate-y-full opacity-0 pointer-events-none', add='translate-y-0 opacity-100 pointer-events-auto')
        self.visible = True

    def hide_panel(self):
        print("尝试隐藏面板")  # 添加调试信息
        self.panel.classes(remove='translate-y-0 opacity-100 pointer-events-auto', add='translate-y-full opacity-0 pointer-events-none')
        self.visible = False

    def add_variable_row(self):
        """添加新的变量行"""
        index = self.next_index
        self.next_index += 1
        with self.panel_content:
            # 为变量行添加背景色，减小行间距和行内元素间距
            with ui.row().classes('items-center mb-1 flex-wrap-nowrap space-x-1 bg-gray-100 p-2 rounded').style('width: 100%;') as row:
                # 为输入框添加 clearable 属性，并设置固定宽度
                var_name_input = ui.input(label='变量名').classes('self-center full-width no-outline flex-1').props('clearable')
                var_value_input = ui.input(label='变量值').classes('self-center full-width no-outline flex-1').props('clearable')
                delete_btn = ui.button(on_click=lambda: self.delete_variable_row(row, index)).props('flat icon=delete').classes('w-auto')

                def update_variable_name(e):
                    # 若旧的变量名存在，移除旧的记录
                    if index in self.variables:
                        del self.variables[index]
                    # 若新变量名和值都不为空，更新字典
                    if var_name_input.value and var_value_input.value:
                        self.variables[index] = {
                            'name': var_name_input.value,
                            'value': var_value_input.value
                        }
                    print(f"当前变量: {self.variables}")

                def update_variable_value(e):
                    # 若旧的变量名存在，移除旧的记录
                    if index in self.variables:
                        del self.variables[index]
                    # 若新变量名和值都不为空，更新字典
                    if var_name_input.value and var_value_input.value:
                        self.variables[index] = {
                            'name': var_name_input.value,
                            'value': var_value_input.value
                        }
                    print(f"当前变量: {self.variables}")

                var_name_input.on('update:model-value', update_variable_name)
                var_value_input.on('update:model-value', update_variable_value)

    def delete_variable_row(self, row, index):
        if index in self.variables:
            del self.variables[index]
        row.delete()
        print(f"当前变量: {self.variables}")

    def update_variables_from_dict(self):
        # 清除现有变量行
        for child in self.panel_content.default_slot.children[:]:
            if isinstance(child, ui.row):
                child.delete()

        # 重新设置下一个序号
        self.next_index = 1

        # 根据字典内容重新创建变量行
        for index in sorted(self.variables.keys()):
            var_name = self.variables[index]['name']
            var_value = self.variables[index]['value']
            with self.panel_content:
                # 为变量行添加背景色，减小行间距和行内元素间距
                with ui.row().classes('items-center mb-1 flex-wrap-nowrap space-x-1 bg-gray-100 p-2 rounded').style('width: 100%;') as row:
                    # 为输入框添加 clearable 属性，并设置固定宽度
                    var_name_input = ui.input(label='变量名', value=var_name).classes('clearable').style('width: 200px;')
                    var_value_input = ui.input(label='变量值', value=var_value).classes('clearable').style('width: 200px;')
                    delete_btn = ui.button(on_click=lambda r=row, i=index: self.delete_variable_row(r, i)).props('flat icon=delete').classes('w-auto')

                    def update_variable_name(e):
                        if index in self.variables:
                            del self.variables[index]
                        if var_name_input.value and var_value_input.value:
                            self.variables[index] = {
                                'name': var_name_input.value,
                                'value': var_value_input.value
                            }
                        print(f"当前变量: {self.variables}")

                    def update_variable_value(e):
                        if index in self.variables:
                            del self.variables[index]
                        if var_name_input.value and var_value_input.value:
                            self.variables[index] = {
                                'name': var_name_input.value,
                                'value': var_value_input.value
                            }
                        print(f"当前变量: {self.variables}")

                    var_name_input.on('update:model-value', update_variable_name)
                    var_value_input.on('update:model-value', update_variable_value)
            self.next_index = max(self.next_index, index + 1)

# 自定义工具栏和内容区样式
ui.add_head_html("""
    <style>
        .custom-editor .q-editor__toolbar {
            background: #4a5568;
            border-radius: 8px 8px 0 0;
        }
        .custom-editor .q-editor__content {
            background-color: #f7fafc;
            border: 1px solid #e2e8f0;
            border-radius: 0 0 8px 8px;
        }
    </style>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            document.querySelectorAll('.code-block').forEach(block => {
                const btn = block.querySelector('.copy-btn');
                btn.onclick = () => {
                    const code = block.querySelector('code').textContent;
                    navigator.clipboard.writeText(code)
                        .then(() => {
                            btn.innerHTML = '<i class="material-icons">done</i>';
                            setTimeout(() => 
                                btn.innerHTML = '<i class="material-icons">content_copy</i>', 
                            2000);
                        });
                };
            });
        });
    </script>
""")

code_snippet = '''
from nicegui import ui

with ui.element('div').classes('columns-3 w-full gap-2'):
    for i, height in enumerate([50, 50, 50, 150, 100, 50]):
        tailwind = f'mb-2 p-2 h-[{height}px] bg-blue-100 break-inside-avoid'
        with ui.card().classes(tailwind):
            ui.label(f'Card #{i+1}')

ui.run()
'''

with ui.row().classes('w-full'):
    with ui.element('div').classes('columns-2 w-full gap-2 h-full flex'): 
        editor = ui.codemirror(language='PLSQL').classes('flex-1 h-full ').props('''theme="darcula" lineNumbers''')
        code = ui.code(code_snippet,language='PLSQL').classes('code-block flex-1') 
        code.set_content(code_snippet)


# 实例化悬浮按钮组件
floating_button = FloatingButton()

# 运行应用
ui.run(title='NiceGUI悬浮按钮示例')